package com.fake_Interviews.controller;

import com.fake_Interviews.module.Login;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class Login_Controller {

    @GetMapping("/me")
    public MyResponse<?> me() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Login login = (Login) subject.getPrincipal();
            Map<String, String> map = new HashMap<>();
            map.put("username", login.getUsername());
            return MyResponse.ok(map);
        }
        return MyResponse.error("未登录");
    }

    @PostMapping("/login")
    public MyResponse<?> login(@RequestBody Map<String, String> map){
        String username = map.get("username");
        String password = map.remove("password");
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SecurityUtils.getSubject().getSession().setTimeout(-1000L);
            return MyResponse.ok(map);
        } catch (AuthenticationException e) {
            return MyResponse.error("用户名密码错误！");
        }
    }

    @GetMapping("/logout")
    public MyResponse<?> logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Login login = (Login) subject.getPrincipal();
            Map<String, String> map = new HashMap<>();
            map.put("username", login.getUsername());
            subject.logout();
            return MyResponse.ok(map);
        }
        return MyResponse.error("未登录");
    }
}
